"""
Database connection and session management for AncientSeeker

SQLAlchemy database setup and base model configuration
"""

from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os

from app.config import settings

# Database engine configuration
engine = create_engine(
    settings.DATABASE_URL,
    connect_args=(
        {"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {}
    ),
)

# Session factory
SessionLocal = sessionmaker(
    autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
)

# Base class for all models
Base = declarative_base()

# Database metadata
metadata = MetaData()


def get_database_session():
    """原始数据库 session 生成器（保留向后兼容，不直接作为 FastAPI 依赖暴露）。"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_database():
    """
    Initialize database by creating all tables.
    This function should be called during application startup.
    """
    # Ensure data directory exists
    data_dir = os.path.dirname(settings.DATABASE_URL.replace("sqlite:///", ""))
    if data_dir:
        os.makedirs(data_dir, exist_ok=True)

    # Create all tables
    Base.metadata.create_all(bind=engine)
    print("Database tables created successfully")


# Alias commonly used dependency name
def get_db():  # pragma: no cover
    """FastAPI 依赖函数，必须直接 yield session，而不是返回生成器对象。"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def reset_database():
    """
    Drop and recreate all database tables.
    WARNING: This will delete all data!
    Only use for development and testing.
    """
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)
    print("Database reset completed")


if __name__ == "__main__":
    # Initialize database when running this file directly
    init_database()
